<?php

/*
 *	Framework namespace
 */
namespace Nano
{
	/*
	 *	JSON Wrapper
	 */
	class JSON
	{
		/*
		 *	$error	srting	Last json error
		 */
		static $error;
		
		/*
		 *	Alias to "self::encode()"
		 */
		static public function __callStatic($name, $args)
		{
			if(empty($args))
			{
				throw new Exception(__CLASS__.': Arguments cannot be empty');
			}
			
			return self::encode(array($name => $args[0]));
		}
		
		/*
		 *	Decode string
		 *
		 *	@param	string	JSON String
		 *	@return	array	Decoded data
		 *
		 *	@thorw
		 *	@static
		 */
		static public function decode($data)
		{
			if(!is_string($data))
			{
				throw new Exception(__METHOD__.': Input data must be a string');
			}
			
			$json = json_decode($data);
			
			if(self::__error())
			{
				throw new Exception(__CLASS__.': '.self::$error);
			}
			
			return $json;
		}
		
		/*
		 *	Encode array
		 *
		 *	@param	array	Data to encode
		 *	@return	string	Encoded data
		 *
		 *	@throw
		 *	@static
		 */
		static public function encode($data)
		{
			if(!is_array($data))
			{
				throw new Exception(__METHOD__.': Input data must be an array');
			}
			
			$json = json_encode($data);
			
			if(self::__error())
			{
				throw new Exception(__CLASS__.': '.self::$error);
			}
			
			return $json;
		}
		
		/*
		 *	Get last error
		 *
		 *	@return	sring
		 *
		 *	@static
		 *	@private
		 */
		static private function __error()
		{
			return self::$error = json_last_error();
		}
	}
}